<?php defined('SYSPATH') or die('No direct script access.');
/*
*
*
*
*/
class Controller_Purchases_Selectpurchase extends Controller_Admin{

 /**
 *手动新建采购单
 *
 */
    public function before()
    {
    	try {
    		  ACL::Required('purchase_order_select');
    	} catch ( HTTP_Exception_403 $e ) {
				Message::error('sorry，你没有权限进这个目录');
    		$this->request->redirect ( URL::base (true) );
    	}
				
        parent::before();
    }
/**
*采购详情
*/
	public function action_singledetail()
	{
		$this->title = "预约单详情";
		$purchase = Config::load('purchase_status');
		$purchase_status = $purchase->purchaseorder;
		$p_detail =$purchase->purchaseorder_details;
		$p_id = $_REQUEST['p_id'];
//        Newerpclientapi::getSupplierContacts($p_id);//联系人
//        Supplierbank::get_supplier_payways_by_supplier_id($p_id);//付款方式及银行账号
//		echo "<pre>";
//		print_r(Supplierbank::get_supplier_payways_by_supplier_id($p_id));
//		echo "<pre>";
//		die;
		$purchase_order = Purchase::select_purchase_info($p_id);
		if(!empty($purchase_order))
		{
			$purchase_order['status'] = $purchase_status[$purchase_order['status']];;
		}
		$supplier       = Purchase::select_supplier($p_id);
		$product_info   = Purchase::select_product($p_id);
		if(!empty($product_info))
		{
			foreach($product_info as &$value){
                $value['status'] = $p_detail[$value['status']];
                $value['rebate'] = $this->action_getRebate($value['supplier'],$value['sku']);
            }
		}
		//$pay_detail     = Purchase::select_pay($p_id);//付款明细
		//$refund_info    = Purchase::select_refund($p_id);//退款明细
		//$union_purchase   = Purchase::select_pay_purchase($p_id);//付款金额汇总
		//查询采购付款单明细
		$purchaseorder_pays = ORM::factory('purchaseorder_pay')->where('purchaseorder_id','=',$p_id)->find_all()->as_array();
		$arr_pays = array();
		$array_pays = array();
		$sum_pay = 0;
		foreach($purchaseorder_pays as $pay){

			$arr_pays['pay_id'] =$pay->id;
			$user = ORM::factory('user',$pay->payer);
 			$arr_pays['pay_user'] =$user->nick;
            if(empty($arr_pays['pay_user'])){
                $ac_nick = json_encode(Acsystemclient::executeAccountSysSql("select nick from gl_users where id = {$pay->ac_user}", NULL), TRUE);
                $arr_pays['pay_user'] = isset($ac_nick[0]['nick'])?$ac_nick[0]['nick']:'系统暂无';
            }
 			$arr_pays['amount_paid'] =round($pay->amount_paid,2);
 			$arr_pays['remark'] =$pay->remark;
 			$arr_pays['pay_date'] =$pay->pay_date;

			$pays = basic::get_pay_way();
			$arr_pays['pay_name'] = (isset($pays[$pay->pay_way]))?$pays[$pay->pay_way]:'';
			$array_pays[] = $arr_pays;
			$sum_pay +=$arr_pays['amount_paid'];
		}
		$gets=array();//添加一个收货明细
		$get = ORM::factory('recieve_invoice')->where('purchaseorder_id','=',$p_id)->find_all()->as_array();
		$i=0;
		foreach ($get as $_get){
	    	$gets_detail = ORM::factory('recieve_detail')->where('recieve_invoice_id','=',$_get->id)->find_all()->as_array();
			foreach ($gets_detail as $get_detail){
				$gets[$i]['getid']=$_get->id;
		    	$gets[$i]['getdetailid']=$get_detail->id;
				$gets[$i]['getman']=Erpuser::nick_by_id($_get->recieve_man);
				$gets[$i]['gettime']=$_get->recieve_time;
				$gets[$i]['sku']=$get_detail->sku;
				$gets[$i]['arrival_quantity']=$get_detail->arrival_quantity;
				$i++;
			}
		}
		$checks=array();//添加一个质检明细
		$checks_detail = ORM::factory('check_quality_detail')->where('purchaseorder_id','=',$p_id)->find_all()->as_array();
		$i=0;
		foreach ($checks_detail as $check_detail){
			$checks[$i]['recieve_detail_id']=$check_detail->recieve_detail_id;
			$checks[$i]['check_man']=Erpuser::nick_by_id($check_detail->check_man);
			$checks[$i]['check_quantity']=$check_detail->check_quantity;
			$checks[$i]['qualified_quantity']=$check_detail->qualified_quantity;
			$checks[$i]['unquality_count']=$check_detail->unquality_count;
			$checks[$i]['invoice_date']=$check_detail->invoice_date;
			$i++;
		}
		$ins=array();//添加一个入库明细
		$_in = ORM::factory('warehouseorder')->where('purchaseorders_id','=',$p_id)->find_all()->as_array();
//		echo "<pre>";print_r($_in);echo "</pre>";die;
		$i=0;
		foreach ($_in as $in){
			$ins[$i]['inid']=$in->id;
			$ins[$i]['inman']=Erpuser::nick_by_id($in->warehouse_man);
			$ins[$i]['inquantity']=$in->warehouse_quantity;
			$ins[$i]['intime']=$in->op_time;
			$ins[$i]['sku']=$in->sku;
			$ins[$i]['single_price']=$in->single_price;
			$ins[$i]['money']=$in->money;
			$ins[$i]['transportation_expense']=$in->transportation_expense;
			$ins[$i]['cost']=$in->cost;
			$i++;
		}
		$logs = DB::select('result_info','username','create_time')->from('op_logs')
            ->where('action','= ','purchaseorders')
            ->where('data_id','=',$p_id)
            ->order_by('id','asc')
            ->execute('newerp')
            ->as_array();
        $view = View::factory('purchase/detail')
						->set('purchase_order',$purchase_order)
						->set('supplier',$supplier)
						->set('product_info',$product_info)
						->set('array_pays',$array_pays)
						->set('sum_pay',$sum_pay)
						->set('gets',$gets)
						->set('logs',$logs)
						->set('checks',$checks)
						->set('ins',$ins);
	
    $this->response->body($view);			
	}

    public function action_getRebate(&$suId,&$sku)
    {
        $data = DB::select('rebate')->from('vmi_supplier_skus')->where('sku','= ',$sku)->where('supplier_id','=',$suId)->execute('newerp')->get('rebate');
        return $data;
    }
    /**
     *  修改运费
     */
    public function action_change_transportation_expense()
    {

            $view = '';
            if(isset($_GET['id']))
            {
                $po = DB::select()->from('purchaseorders')
                    ->where('id','=',trim($_GET['id']))
                    ->execute('newerp')
                    ->current();
                if($po)
                {
                    $view = View::factory('purchase/transportationexpense');
                    $view->set('po',$po);
                }
            }
            if(isset($_POST['id'])
                and isset($_POST['tran_exp']))
            {
               $po_status = DB::update('purchaseorders')
                   ->set(array('transportation_expense'=>trim($_POST['tran_exp'])))
                   ->where('id','=',trim($_POST['id']))
                   ->execute('newerp');

                if($po_status)
                {
                   $view = json_encode(array('code'=>200,'msg'=>'ok'));
                }
            }
            $this->response->body($view);

    }

    public function action_saveTaxRate()
    {
        $id = $_POST['id'];
        $real_tax_rate = $_POST['real_tax_rate'];
        $p_id = $_POST['p_id'];
        $result = DB::update('purchaseorder_details')->set(array('real_tax_rate'=>$real_tax_rate))->where('id','=',$id)->execute('newerp');
        if($result!==false){
            echo "<script>alert('操作成功');location.href='".URL::site()."purchases/selectpurchase/singledetail?p_id=$p_id';</script>";die;
        }else{
            echo "<script>alert('操作失败');location.href='".URL::site()."purchases/selectpurchase/singledetail?p_id=$p_id';</script>";die;
        }
    }
}
